package middleware

import (
	"fmt"
	"stacks/database"
	"stacks/models"
	"stacks/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

// RBAC RBAC权限验证中间件
func RBAC() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取用户信息
		userID, _, tenantID := GetUserInfo(c)
		if userID == 0 || tenantID == 0 {
			utils.Unauthorized(c, "用户信息获取失败")
			c.Abort()
			return
		}

		// 获取请求路径和方法
		path := c.Request.URL.Path
		method := c.Request.Method

		// 检查用户是否有权限访问该接口
		hasPermission, err := checkPermission(userID, tenantID, path, method)
		if err != nil {
			utils.InternalError(c, "权限检查失败")
			c.Abort()
			return
		}

		if !hasPermission {
			utils.Forbidden(c, "没有访问权限")
			c.Abort()
			return
		}

		c.Next()
	}
}

// checkPermission 检查用户权限
func checkPermission(userID, tenantID uint, path, method string) (bool, error) {
	// 如果是超级管理员，直接放行
	if isSuperAdmin(userID, tenantID) {
		return true, nil
	}

	// 获取用户的所有权限
	permissions, err := getUserPermissions(userID, tenantID)
	if err != nil {
		return false, err
	}

	// 检查权限
	for _, permission := range permissions {
		if permission.Type == 2 && // 接口权限
			permission.Path != "" &&
			strings.HasPrefix(path, permission.Path) &&
			(permission.Method == "" || permission.Method == method) {
			return true, nil
		}
	}

	return false, nil
}

// isSuperAdmin 检查是否为超级管理员
func isSuperAdmin(userID, tenantID uint) bool {
	fmt.Println(userID, tenantID)
	// 这里可以定义超级管理员的判断逻辑
	// 例如：用户ID为1的用户是超级管理员
	return userID == 1
}

// getUserPermissions 获取用户的所有权限
func getUserPermissions(userID, tenantID uint) ([]models.SysPermission, error) {
	var permissions []models.SysPermission

	err := database.GetDB().
		Joins("JOIN role_permissions ON role_permissions.permission_id = permissions.id").
		Joins("JOIN user_roles ON user_roles.role_id = role_permissions.role_id").
		Where("user_roles.user_id = ? AND permissions.tenant_id = ? AND permissions.status = 1",
			userID, tenantID).
		Find(&permissions).Error

	return permissions, err
}
